import { Suspense } from 'react';
import { BrowserRouter, type RouteObject, useRoutes } from 'react-router-dom';
import routes from './routes';
import type { CustomRouteObject } from './types';
import AuthGuard from './AuthGuard';

// 加载指示器组件
const LoadingFallback = () => <div className="loading">加载中...</div>;

// 根据自定义路由配置生成带权限验证的路由
const generateRoutesWithAuth = (routes: CustomRouteObject[]): RouteObject[] => {
  return routes.map((route) => {
    const { meta, children, ...restRoute } = route;

    // 处理带有 children 的路由
    if (children && children.length > 0) {
      return {
        ...restRoute,
        children: generateRoutesWithAuth(children),
      };
    }

    // 处理需要权限的路由
    if (meta?.requiresAuth) {
      return {
        ...restRoute,
        element: (
          <AuthGuard requiresAuth={meta.requiresAuth} permissions={meta.permissions}>
            {restRoute.element}
          </AuthGuard>
        ),
      };
    }

    // 不需要特殊处理的路由直接返回
    return restRoute;
  });
};

// 路由渲染组件
const AppRoutes = () => {
  // 将自定义路由配置转换为带有权限验证的路由
  const processedRoutes = generateRoutesWithAuth(routes as CustomRouteObject[]);

  // 使用 useRoutes 渲染路由
  const element = useRoutes(processedRoutes);

  return <Suspense fallback={<LoadingFallback />}>{element}</Suspense>;
};

// 路由提供者组件
const RouterProvider = () => {
  return (
    <BrowserRouter>
      <AppRoutes />
    </BrowserRouter>
  );
};

export default RouterProvider;
